package classification

import (
	"context"
	"github.com/pkg/errors"
	"yangming-college/app/speciality/cmd/v1/api/internal/svc"
	"yangming-college/app/speciality/cmd/v1/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ClassificationLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewClassificationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassificationLogic {
	return &ClassificationLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ClassificationLogic) Classification(req *types.IdReq) (resp []types.ClassificationInfo, err error) {
	// 获得细分领域下的所有类别
	//todo 算法优化 or 存redis
	var classificationId []int
	var classificationInfo []types.ClassificationInfo
	err = l.svcCtx.DB.Table("speciality_classification_relation").Select("classification_id").Where("speciality_id = ?", req.Id).Find(&classificationId).Error
	if err != nil {
		return nil, errors.Wrapf(err, "speciality v1 api Classification error 1")
	}
	err = l.svcCtx.DB.Table("classification").Find(&classificationInfo, classificationId).Error
	if err != nil {
		return nil, errors.Wrapf(err, "speciality v1 api Classification error 2")
	}
	for i, o := range classificationInfo {
		var classificationChildren []types.ClassificationInfo
		err := l.svcCtx.DB.Table("classification").Where("parent_id = ?", o.Id).Find(&classificationChildren).Error
		if err != nil {
			return nil, errors.Wrapf(err, "speciality v1 api Classification error 3")
		}
		classificationInfo[i].Children = classificationChildren
	}

	return classificationInfo, nil
}
